<template>
  <div class="w-full flex flex-col">
    <!-- stem -->
    <div
      class="stem w-full inline-block text-333"
      style="white-space: break-spaces; word-break: break-all"
      v-html="stem"
    ></div>
    <!-- stem-ogOps -->
    <div class="stem-options mt-20px">
      <!-- 样式一 -->
      <div v-if="['homework_todo_question_english', 'exercise_practice_english'].includes(master)">
        <div
          v-for="(option, index) in stemOgOps"
          :key="index"
          :class="index < stemOgOps.length - 1 ? 'mb-14px' : ''"
          @touchstart="choose(answerIndex, option.index)"
        >
          <CustomRadio
            :value="isChose(answerIndex, option.index) ? option.index : ''"
            :label="option.index"
            :text="option.html"
          />
        </div>
      </div>
      <!-- 样式二 -->
      <div
        v-else-if="
          ['homework_detail_english', 'exercise_record_english', 'wqbook_detail_english'].includes(
            master
          )
        "
      >
        <div
          v-for="(option, index) in stemOgOps"
          :key="index"
          class="flex items-center"
          :class="index < stemOgOps.length - 1 ? 'mb-14px' : ''"
          @touchstart="choose(answerIndex, option.index)"
        >
          <img
            class="mr-6px"
            :src="`static/icons/choice-${
              isChose(answerIndex, option.index)
                ? props.readonly
                  ? isCorrect(answerIndex, option.index)
                    ? 'right'
                    : 'wrong'
                  : 'right'
                : props.readonly
                ? isCorrect(answerIndex, option.index)
                  ? 'right'
                  : 'empty'
                : 'empty'
            }.png`"
            style="width: 0.22rem; height: 0.22rem"
          />
          <span
            :class="
              isChose(answerIndex, option.index)
                ? props.readonly
                  ? isCorrect(answerIndex, option.index)
                    ? 'text-30C9A1'
                    : 'text-FF4040'
                  : 'text-30C9A1'
                : props.readonly
                ? isCorrect(answerIndex, option.index)
                  ? 'text-30C9A1'
                  : 'empty'
                : 'empty'
            "
            >{{ option.html }}</span
          >
        </div>
      </div>
      <!-- 样式三 -->
      <div v-else>
        <div
          v-for="(option, index) in stemOgOps"
          :key="index"
          class="item flex items-center text-333 p-20px box-border bg-F4F7FB"
          :class="[
            isChose(answerIndex, option.index, option.html)
              ? props.readonly
                ? isCorrect(answerIndex, option.index, option.html)
                  ? 'bg-51C3FF-70 sucess'
                  : 'bg-FF4040-70 error'
                : 'bg-51C3FF-70 sucess '
              : '',
            props.readonly && isCorrect(answerIndex, option.index, option.html) ? 'sucessing' : ''
          ]"
          @click="choose(answerIndex, option.index, $event)"
        >
          <div></div>
          <span class="">（{{ option.index }}）</span><span v-html="option.html"></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CustomRadio from '@/components/radio'
import { generateStudentAnswer } from '@/utils/question'

export default {
  components: {
    CustomRadio
  },
  inject: ['emit', 'props'],
  data() {
    return {}
  },
  computed: {
    master() {
      const { master } = this.props

      return master
    },
    stem() {
      const { index: questionIndex, data: stem, answerIndex } = this.props
      const { html = '', label = '' } = stem
      let stemText = '' // 题干文字
      let stemHtml = '' // 题干模板

      try {
        stemText = html
          .replace(
            /<p[\w\W]*?>/,
            label
              ? `<p style=""><span class="question-type inline-block px-8px py-2px text-51C3FF">${label}</span> <span>${
                  questionIndex != -1 ? questionIndex + 1 + '.' : ''
                }</span>`
              : `<p style=""><span>${questionIndex != -1 ? questionIndex + 1 + '.' : ''}</span>`
          )
          .replace(/<p/g, '<p class="paragraph"')
          .replace(/<[\w\W]*?>/gi, '') // 清空html标签
          .trim() // 清空首尾空格
          .replace('&nbsp;', '') // 清空空格标记

        if (!stemText && html.indexOf('<img') != -1) {
          stemText = '[题干图片]'
        }

        stemHtml = html
          .replace(
            /<p[\w\W]*?>/,
            label
              ? `<p style=""><span class="question-type inline-block px-8px py-2px text-51C3FF">${label}</span> <span>${
                  questionIndex != -1 ? questionIndex + 1 + '.' : ''
                }</span>`
              : `<p style=""><span>${questionIndex != -1 ? questionIndex + 1 + '.' : ''}</span>`
          )
          .replace(/<p/g, '<p class="paragraph"')
      } catch (error) {}

      return stemText ? stemHtml : `${answerIndex + 1}.`
    },
    stemOgOps() {
      const { data: stem } = this.props

      const { og = {} } = stem

      if (JSON.stringify(og) === '{}') return null

      const { ogOps = [] } = og

      return ogOps
    },
    answer() {
      const { answer } = this.props

      return answer
    },
    answerIndex() {
      const { answerIndex } = this.props

      return answerIndex
    },
    studentAnswer() {
      const { studentAnswer } = this.props

      return studentAnswer
    }
  },
  watch: {
    stem() {
      this.$nextTick(() => MathJye.LayOut(document.body))
    }
  },
  mounted() {
    this.$nextTick(() => MathJye.LayOut(document.body))
  },
  methods: {
    isChose(anSqsIndex = 0, answer, answerOriginHtml) {
      const getChoseAnswer = (anSqsIndex = 0) => {
        const { studentAnswer } = this

        if (!studentAnswer) return ''

        try {
          return studentAnswer.anSqs[anSqsIndex].ans[0].anStudent
        } catch (error) {
          return ''
        }
      }

      try {
        if (answerOriginHtml) {
          const dataAnswer = answerOriginHtml.match(/data-answer="[\w\W]*?"/)
          if (dataAnswer) {
            answer = dataAnswer[0].replace('data-answer="', '').replace('"', '')
          }
        }
      } catch (error) {
        console.error(error)
      }

      if (getChoseAnswer(anSqsIndex) === answer) {
        return true
      } else {
        return false
      }
    },
    isCorrect(anSqsIndex = 0, answer, answerOriginHtml) {
      const getAnswer = (anSqsIndex = 0) => {
        const { answer } = this

        try {
          return answer.anSqs[anSqsIndex].ans[0].anStudent
            .replace(/<[\w\W]*?>/gi, '') // 清空html标签
            .trim() // 清空首尾空格
            .replace('&nbsp;', '') // 清空空格标记
        } catch (error) {
          return ''
        }
      }

      try {
        if (answerOriginHtml) {
          const dataAnswer = answerOriginHtml.match(/data-answer="[\w\W]*?"/)
          if (dataAnswer) {
            answer = dataAnswer[0].replace('data-answer="', '').replace('"', '')
          }
        }
      } catch (error) {
        console.error(error)
      }

      if (getAnswer(anSqsIndex) === answer) {
        return true
      } else {
        return false
      }
    },
    choose(anSqsIndex = 0, answer, event) {
      const { readonly = false } = this.props

      if (readonly) return

      if (!answer) return

      const { studentAnswer } = this

      if (!studentAnswer) {
        this.emit('change-student-answer', {
          answer: {
            anSqs: []
          },
          canNext: false
        })
      }

      try {
        if (event) {
          // 获取当前节点以及所有子节点
          const flatDom = (dom, totalDom = []) => {
            if (dom instanceof HTMLElement) {
              totalDom.push(dom)
              const children = dom.children
              for (let i = 0; i < children.length; i++) {
                flatDom(children.item(i), totalDom)
              }
            }

            return totalDom
          }

          // 从dom节点获取答案
          const getAnswerFromDom = (dom) => {
            const domArray = flatDom(dom)

            if (Array.isArray(domArray)) {
              const op = domArray.find((dom) => dom.className === 'qml-op')
              if (op) {
                const { answer } = op.dataset
                return answer
              }
            }
          }

          const rootDom = event.target
          const answerFromDom = getAnswerFromDom(rootDom)
          answer = answerFromDom ? answerFromDom : answer
        }
      } catch (error) {
        console.error(error)
      }

      const studentAnswerTemp = generateStudentAnswer({
        anSqs: studentAnswer.anSqs,
        anSqsIndex,
        ansIndex: 0,
        answer
      })

      // 判断所有选择题是否做完
      let canNext = true
      const { anSqs = [] } = studentAnswerTemp

      if (anSqs.length < this.answer.anSqs.length) {
        canNext = false
      }

      if (this.answer.anSqs.length > 1 && anSqs.length === this.answer.anSqs.length) {
        let arr = []
        anSqs.forEach((item) => {
          arr = arr.concat(item.ans)
        })

        if (arr.some((i) => !i.anStudent)) {
          canNext = false
        }
      }

      this.emit('change-student-answer', {
        answer: studentAnswerTemp,
        status: 1,
        canNext
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.stem {
  font-size: 26px !important;
  line-height: 28px;
}

/deep/ .stem {
  .question-type {
    font-size: 26px !important;
    background-color: rgba(81, 195, 255, 0.1);
    border-radius: 4px;
    line-height: 28px;
  }

  .paragraph {
    line-height: 34px;
    white-space: normal;

    &:first-child > br + img {
      margin-top: 10px;
    }

    &:not(:first-child) {
      margin-top: 10px;
    }

    audio {
      display: block;
      padding: 8px 0 0 0;
    }
  }
}

.stem-options {
  font-size: 26px;
  line-height: 26px;
  word-break: break-all;

  .item {
    border-radius: 8px;

    &:not(:last-child) {
      margin-bottom: 20px;
    }
  }

  .sucess {
    background: rgba(48, 201, 161, 0.1);
    position: relative;

    &::before {
      content: '';
      background: url('@/assets/exercise/sucessimg.png') no-repeat;
      background-size: 44px 30px;
      position: absolute;
      top: 0;
      right: 0;
      width: 44px;
      height: 30px;
      z-index: 99;
    }
  }

  .error {
    background: rgba(255, 64, 64, 0.1);
    position: relative;

    &::before {
      content: '';
      background: url('@/assets/exercise/errimg.png') no-repeat;
      background-size: 44px 30px;
      position: absolute;
      top: 0;
      right: 0;
      width: 44px;
      height: 30px;
      z-index: 99;
    }
  }

  .sucessing {
    background: rgba(48, 201, 161, 0.1);
    position: relative;

    &::before {
      content: '';
      background: url('@/assets/exercise/sucessimg.png') no-repeat;
      background-size: 44px 30px;
      position: absolute;
      top: 0;
      right: 0;
      width: 44px;
      height: 30px;
      z-index: 99;
    }
  }
}
</style>
